package com.xinzhidi.web.netty.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinzhidi.common.constant.AgreementConstants;
import com.xinzhidi.common.core.domain.model.LoginUser;
import com.xinzhidi.common.core.page.TableDataInfo;
import com.xinzhidi.common.exception.ServiceException;
import com.xinzhidi.common.utils.DateUtils;
import com.xinzhidi.common.utils.SecurityUtils;
import com.xinzhidi.common.utils.StringUtils;
import com.xinzhidi.common.utils.bean.BeanUtils;
import com.xinzhidi.common.utils.file.FileTypeUtils;
import com.xinzhidi.web.equipment.domain.vo.EquipmentInfoVo;
import com.xinzhidi.web.equipment.service.EquipmentService;
import com.xinzhidi.web.netty.entity.*;
import com.xinzhidi.web.netty.entity.dto.AgreementHouseholdValveAddDto;
import com.xinzhidi.web.netty.entity.dto.AgreementHouseholdValveListDto;
import com.xinzhidi.web.netty.entity.dto.AgreementHouseholdValveUpdDto;
import com.xinzhidi.web.netty.entity.householdValve.ValveDataRead;
import com.xinzhidi.web.netty.entity.po.AgreementCommandPo;
import com.xinzhidi.web.netty.entity.vo.AgreementHouseholdValveInfoVo;
import com.xinzhidi.web.netty.entity.vo.AgreementHouseholdValveListVo;
import com.xinzhidi.web.netty.mapper.AgreementHouseholdValveMapper;
import com.xinzhidi.web.netty.utils.FormatData;
import com.xinzhidi.web.netty.utils.HexadecimalUtil;
import com.xinzhidi.web.netty.utils.NettyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 户用阀门协议-（实时数据）Service业务层处理
 *
 * @author cx
 * @date 2023-06-13
 */
@Service
public class AgreementHouseholdValveService extends ServiceImpl<AgreementHouseholdValveMapper, AgreementHouseholdValve> {

    @Autowired
    private AgreementHouseholdValveMapper agreementHouseholdValveMapper;

    @Autowired
    private AgreementHouseholdValveHistoryService householdValveHistoryService;

    @Autowired
    private AgreementCommandService commandService;

    @Autowired
    private AgreementCommandFieldService commandFieldService;

    @Autowired
    private DeviceInstructionService deviceInstructionService;

    @Autowired
    private EquipmentService equipmentService;

    /**
     * 查询户用阀门协议-（实时数据）
     *
     * @param id 户用阀门协议-（实时数据）主键
     * @return 户用阀门协议-（实时数据）
     */
    public AgreementHouseholdValveInfoVo selectAgreementHouseholdValveById(Long id) {
        AgreementHouseholdValve agreementHouseholdValve = agreementHouseholdValveMapper.selectById(id);
        AgreementHouseholdValveInfoVo infoVo = new AgreementHouseholdValveInfoVo();
        BeanUtils.copyProperties(agreementHouseholdValve, infoVo);
        return infoVo;
    }

    public AgreementHouseholdValve getAgreementHouseholdValve(AgreementHouseholdValveListDto dto) {
        AgreementHouseholdValve agreementHouseholdValve = agreementHouseholdValveMapper.selectOne(buildGenTableQueryWrapper(dto));
        return agreementHouseholdValve;
    }


    /**
     * 查询户用阀门协议-（实时数据）列表
     *
     * @param dto 查询户用阀门协议-（实时数据）dto
     * @return 户用阀门协议-（实时数据）
     */
    public TableDataInfo<AgreementHouseholdValveListVo> selectAgreementHouseholdValveList(AgreementHouseholdValveListDto dto) {
        LambdaQueryWrapper<AgreementHouseholdValve> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(StringUtils.isNotEmpty(dto.getType()), AgreementHouseholdValve::getType, dto.getType());
        wrapper.like(StringUtils.isNotEmpty(dto.getProtocolName()), AgreementHouseholdValve::getProtocolName, dto.getProtocolName());
        wrapper.like(StringUtils.isNotEmpty(dto.getInstructName()), AgreementHouseholdValve::getInstructName, dto.getInstructName());
        wrapper.eq(StringUtils.isNotEmpty(dto.getInstructType()), AgreementHouseholdValve::getInstructType, dto.getInstructType());
        wrapper.eq(dto.getPlotId() != null, AgreementHouseholdValve::getPlotId, dto.getPlotId());
        wrapper.eq(dto.getBuildId() != null, AgreementHouseholdValve::getBuildId, dto.getBuildId());
        wrapper.eq(dto.getUnitId() != null, AgreementHouseholdValve::getUnitId, dto.getUnitId());
        wrapper.eq(dto.getHouseholdId() != null, AgreementHouseholdValve::getHouseholdId, dto.getHouseholdId());
        wrapper.eq(StringUtils.isNotEmpty(dto.getDeviceType()), AgreementHouseholdValve::getDeviceType, dto.getDeviceType());
        wrapper.eq(StringUtils.isNotEmpty(dto.getAddress()), AgreementHouseholdValve::getAddress, dto.getAddress());
        wrapper.eq(StringUtils.isNotEmpty(dto.getInstructionSet()), AgreementHouseholdValve::getInstructionSet, dto.getInstructionSet());
        wrapper.eq(StringUtils.isNotEmpty(dto.getJsonData()), AgreementHouseholdValve::getJsonData, dto.getJsonData());
        wrapper.orderByDesc(AgreementHouseholdValve::getId);
        return TableDataInfo.getDataTable(agreementHouseholdValveMapper.selectList(wrapper), (domain -> {
            AgreementHouseholdValveListVo vo = new AgreementHouseholdValveListVo();
            BeanUtils.copyProperties(domain, vo);
            return vo;
        }));
    }

    /**
     * 新增户用阀门协议-（实时数据）
     *
     * @param dto 新增户用阀门协议-（实时数据）dto
     * @return 结果
     */
    public int insertAgreementHouseholdValve(AgreementHouseholdValveAddDto dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        AgreementHouseholdValve agreementHouseholdValve = new AgreementHouseholdValve();
        BeanUtils.copyProperties(dto, agreementHouseholdValve);
        agreementHouseholdValve.setCreateBy(loginUser.getUserId().toString());
        agreementHouseholdValve.setCreateTime(DateUtils.getNowDate());
        return agreementHouseholdValveMapper.insert(agreementHouseholdValve);
    }

    /**
     * 修改户用阀门协议-（实时数据）
     *
     * @param dto 修改户用阀门协议-（实时数据）dto
     * @return 结果
     */
    public int updateAgreementHouseholdValve(AgreementHouseholdValveUpdDto dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        AgreementHouseholdValve agreementHouseholdValve = new AgreementHouseholdValve();
        BeanUtils.copyProperties(dto, agreementHouseholdValve);
        agreementHouseholdValve.setUpdateBy(loginUser.getUserId().toString());
        agreementHouseholdValve.setUpdateTime(DateUtils.getNowDate());
        return agreementHouseholdValveMapper.updateById(agreementHouseholdValve);
    }

    /**
     * 批量删除户用阀门协议-（实时数据）
     *
     * @param ids 需要删除的户用阀门协议-（实时数据）主键
     * @return 结果
     */
    public int deleteAgreementHouseholdValveByIds(Long[] ids) {
        return agreementHouseholdValveMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除户用阀门协议-（实时数据）信息
     *
     * @param id 户用阀门协议-（实时数据）主键
     * @return 结果
     */
    public int deleteAgreementHouseholdValveById(Long id) {
        return agreementHouseholdValveMapper.deleteById(id);
    }

    private LambdaQueryWrapper<AgreementHouseholdValve> buildGenTableQueryWrapper(AgreementHouseholdValveListDto dto) {
        LambdaQueryWrapper<AgreementHouseholdValve> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(dto.getProtocolName()), AgreementHouseholdValve::getProtocolName, dto.getProtocolName())
                .like(StringUtils.isNotBlank(dto.getInstructName()), AgreementHouseholdValve::getInstructName, dto.getInstructName())
                .eq(StringUtils.isNotBlank(dto.getInstructType()), AgreementHouseholdValve::getInstructType, dto.getInstructType())
                .eq(StringUtils.isNotNull(dto.getDtuId()), AgreementHouseholdValve::getDtuId, dto.getDtuId())
                .eq(StringUtils.isNotBlank(dto.getAddress()), AgreementHouseholdValve::getAddress, dto.getAddress());
        return wrapper;
    }

    /**
     * 户用阀门协议解析
     *
     * @param deviceInstruction 下发指令
     * @param message           消息
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> receiveHouseholdValve(String message, DeviceInstruction deviceInstruction) {
        //1：获取该回复指令的下发指令是哪条数据(户用阀门协议-历史数据表type为1的最后一条数据
        //2：获取协议指令表（agreement_command）、协议指令字段表（agreement_command_field）数据
        //3：解析数据，组装实体类
        //4:保存户用阀门协议-实时数据表（agreement_household_valve）、户用阀门协议-历史数据表（agreement_household_valve_history）
        //5：更新指令发送表（device_instruction）状态

//        LambdaQueryWrapper<AgreementHouseholdValveHistory> wrapper = new LambdaQueryWrapper<>();
//        wrapper.orderByDesc(AgreementHouseholdValveHistory::getCreateTime).last(" limit 1");

        LambdaQueryWrapper<AgreementCommand> commandWrapper = new LambdaQueryWrapper<>();
        commandWrapper.eq(AgreementCommand::getType, AgreementConstants.InstructionType.RECEIVE)
                .eq(AgreementCommand::getProtocolType, deviceInstruction.getProtocolType())
                .eq(AgreementCommand::getInstructType, deviceInstruction.getInstructType());
        AgreementCommand command = commandService.getOne(commandWrapper);

        LambdaQueryWrapper<AgreementCommandField> commandFieldLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commandFieldLambdaQueryWrapper.eq(AgreementCommandField::getCommandId, command.getId())
                .orderByAsc(AgreementCommandField::getSort);
        List<AgreementCommandField> commandFieldList = commandFieldService.list(commandFieldLambdaQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        for (AgreementCommandField commandField : commandFieldList) {
            Integer startNum = commandField.getStartNum();
            Integer endNum = commandField.getEndNum();
            String value = NettyUtils.getByteStr(startNum, endNum, message, commandField);
            FileTypeUtils.setValueByType(commandField.getFieldEnglish(), commandField.getFieldType(), map, value);
        }
        //保存户用阀门协议-实时数据表（agreement_household_valve）、户用阀门协议-历史数据表（agreement_household_valve_history）
        saveAgreementHouseholdValve(message, map, command, deviceInstruction);
        return map;
    }

    /**
     * 保存户用阀门协议-实时数据表（agreement_household_valve）、户用阀门协议-历史数据表（agreement_household_valve_history）
     */
    private void saveAgreementHouseholdValve(
            String message,
            Map<String, Object> map,
            AgreementCommand command,
            DeviceInstruction deviceInstruction) {
        AgreementHouseholdValve householdValve;
        //判断户用阀门实时数据是否已存在，存在则更新，不存在则新增
        AgreementHouseholdValveListDto dto = new AgreementHouseholdValveListDto();
        dto.setDtuId(deviceInstruction.getDtuId());
        dto.setAddress(deviceInstruction.getAddress());
        dto.setInstructType(command.getInstructType());
        householdValve = this.getAgreementHouseholdValve(dto);
        if (householdValve != null) {
            householdValve.setInstructionSet(message);
            householdValve.setJsonData(JSON.toJSONString(map));
            householdValve.setUpdateTime(DateUtils.getNowDate());
        } else {
            householdValve = new AgreementHouseholdValve();
            householdValve.setDeviceInstructionId(deviceInstruction.getId());
            householdValve.setDtuId(deviceInstruction.getDtuId());
            householdValve.setProtocolName(command.getProtocolName());
            householdValve.setInstructType(command.getInstructType());
            householdValve.setInstructName(command.getInstructName());
            householdValve.setPlotId(deviceInstruction.getPlotId());
            householdValve.setBuildId(deviceInstruction.getBuildId());
            householdValve.setUnitId(deviceInstruction.getUnitId());
            householdValve.setHouseholdId(deviceInstruction.getHouseholdId());
            householdValve.setDeviceType(command.getDeviceType());
            householdValve.setAddress(deviceInstruction.getAddress());
            householdValve.setInstructionSet(message);
            householdValve.setJsonData(JSON.toJSONString(map));
        }

        if (this.saveOrUpdate(householdValve)) {
            LambdaQueryWrapper<AgreementCommand> commandWrapper = new LambdaQueryWrapper<>();
            commandWrapper.eq(AgreementCommand::getType, AgreementConstants.InstructionType.RECEIVE)
                    .eq(AgreementCommand::getProtocolType, deviceInstruction.getProtocolType())
                    .eq(AgreementCommand::getInstructType, deviceInstruction.getInstructType());
            command = commandService.getOne(commandWrapper);
            //保存户用阀门协议-历史数据表（agreement_household_valve_history）
            AgreementHouseholdValveHistory householdValveHistory = new AgreementHouseholdValveHistory();
            householdValveHistory.setDeviceInstructionId(deviceInstruction.getId());
            householdValveHistory.setDtuId(deviceInstruction.getDtuId());
            householdValveHistory.setProtocolName(command.getProtocolName());
            householdValveHistory.setInstructType(command.getInstructType());
            householdValveHistory.setInstructName(command.getInstructName());
            householdValveHistory.setPlotId(deviceInstruction.getPlotId());
            householdValveHistory.setBuildId(deviceInstruction.getBuildId());
            householdValveHistory.setUnitId(deviceInstruction.getUnitId());
            householdValveHistory.setHouseholdId(deviceInstruction.getHouseholdId());
            householdValveHistory.setDeviceType(command.getDeviceType());
            householdValveHistory.setAddress(deviceInstruction.getAddress());
            householdValveHistory.setInstructionSet(message);
            householdValveHistory.setPrefix(command.getPrefix());
            householdValveHistory.setDeviceType(command.getDeviceType());
            householdValveHistory.setControlCode(command.getControlCode());
            householdValveHistory.setLengthField(command.getLengthField());
            householdValveHistory.setStartChar(command.getStartChar());
            householdValveHistory.setJsonData(JSON.toJSONString(map));
            householdValveHistory.setDataFieldInstruct(command.getDataFieldInstruct());
            householdValveHistory.setEndMark(command.getEndMark());
            householdValveHistoryService.save(householdValveHistory);
        }
        deviceInstruction.setStatus(AgreementConstants.InstructSendingState.RETURN_TO_NORMAL);
        deviceInstructionService.updateById(deviceInstruction);
    }

    /**
     * 根据条件查询户用阀门协议-实时数据表（读阀门数据:开度，温度））
     */
    public ValveDataRead getValveDataRead(AgreementHouseholdValveListDto dto) {
        return baseMapper.getValveDataRead(dto);
    }

    /**
     * 户用阀门-【写阀门地址】指令下发
     */
    public boolean writeValveAddress(Long dtuId, String oldAddress, String newAddress) {
        return this.saveAddressDeviceInstruction(AgreementConstants.AgreementType.HOUSEHOLD_VALVE, "9", dtuId, oldAddress, newAddress);
    }

    /**
     * 户用阀门-【读阀门地址】指令下发
     */
    public boolean readValveAddress(Long dtuId) {
        return this.readAddress(AgreementConstants.AgreementType.HOUSEHOLD_VALVE, "10", dtuId);
    }

    /**
     * 户用阀门-【读阀门当前AD值】指令下发
     */
    public boolean readADValue(Long dtuId, String address) {
        return this.saveDeviceInstruction(dtuId, address, "11", "");
    }

    /**
     * 户用阀门-【读 阀门信息（工作模式等）】指令下发
     */
    public boolean readValue(Long dtuId, String address) {
        return this.saveDeviceInstruction(dtuId, address, "4", "");
    }

    /**
     * 户用阀门-【读传感器数据】指令下发
     */
    public boolean readSensorValue(Long dtuId, String address) {
        return this.saveDeviceInstruction(dtuId, address, "12", "");
    }

    /**
     * 户用阀门-【写阀门校准开度AD值】指令下发
     */
    public boolean writeCalibrate(Long dtuId, String address, Integer kadh, Integer kadl, Integer gadh, Integer gadl) {
        String value = FormatData.tenToHexadecimal(kadh, 1)
                + FormatData.tenToHexadecimal(kadl, 1)
                + FormatData.tenToHexadecimal(gadh, 1)
                + FormatData.tenToHexadecimal(gadl, 1);
        return this.saveDeviceInstruction(dtuId, address, "13", value);
    }

    /**
     * 户用阀门-【阀门工作模式】指令下发
     */
    public boolean valveOperatingMode(Long dtuId, String address, String mode) {
        return this.saveDeviceInstruction(dtuId, address, "1", mode);
    }

    /**
     * 户用阀门-【阀门掉电开度】指令下发
     */
    public boolean writeValvePowerDown(Long dtuId, String address, Integer valveOpen) {
        String value = FormatData.tenToHexadecimal(valveOpen, 1);
        return this.saveDeviceInstruction(dtuId, address, "7", value);
    }

    /**
     * 户用阀门-【读阀门数据（开度，温度）】指令下发
     */
    public boolean readValve(Long dtuId, String address) {
        return this.saveDeviceInstruction(dtuId, address, "2", "");
    }

    /**
     * 户用阀门-【写 阀门数据（开度）】指令下发
     */
    public boolean writeValveOpen(Long dtuId, String address, Integer valveOpen) {
        //下发的时候，数据需乘以系数10
        valveOpen = valveOpen * 10;
        String value = FormatData.tenToHexadecimal(Integer.valueOf(valveOpen), 2);
        return this.saveDeviceInstruction(dtuId, address, "3", value);
    }

    /**
     * 户用阀门-【清零指令】指令下发
     */
    public boolean clearInstruction(Long dtuId, String address) {
        return this.saveDeviceInstruction(dtuId, address, "5", "");
    }

    /**
     * 户用阀门-【阀门维护】指令下发
     */
    public boolean valveMaintenance(Long dtuId, String address) {
        return this.saveDeviceInstruction(dtuId, address, "6", "");
    }

    /**
     * 户用阀门-【写 阀门断电开度】指令下发
     */
    public boolean writeValvePowerOpen(Long dtuId, String address, Integer valveOpen) {
        String value = FormatData.tenToHexadecimal(Integer.valueOf(valveOpen), 2);
        return this.saveDeviceInstruction(dtuId, address, "7", value);
    }

    /**
     * 户用阀门-【写 阀门时间】指令下发
     */
    public boolean writeValveTime(Long dtuId, String address, String yy, String mm, String dd, String hh, String mi, String ss) {
        String value = FormatData.tenToHexadecimal(Integer.valueOf(yy), 1)
                + FormatData.tenToHexadecimal(Integer.valueOf(mm), 1)
                + FormatData.tenToHexadecimal(Integer.valueOf(dd), 1)
                + FormatData.tenToHexadecimal(Integer.valueOf(hh), 1)
                + FormatData.tenToHexadecimal(Integer.valueOf(mi), 1)
                + FormatData.tenToHexadecimal(Integer.valueOf(ss), 1);
        return this.saveDeviceInstruction(dtuId, address, "8", value);
    }

    /**
     * 通用组装写地址指令表数据
     */
    public boolean saveAddressDeviceInstruction(String protocolType, String instructType, Long dtuId, String oldAddress, String newAddress) {
        //获取设备信息
        EquipmentInfoVo infoVo = equipmentService.getEquipmentInfoVo(dtuId, oldAddress);

        AgreementCommandPo agreementCommandPo = new AgreementCommandPo();
        agreementCommandPo.setProtocolType(protocolType);
        agreementCommandPo.setType(AgreementConstants.InstructionType.SEND);
        agreementCommandPo.setInstructType(instructType);
        AgreementCommand command = commandService.getProtocolInstruction(agreementCommandPo);
        if (command == null) {
            throw new ServiceException("指令不存在！");
        }
        String message = "";
        message = command.getPrefix() + command.getStartChar() + command.getDeviceType() + newAddress
                + command.getControlCode() + command.getLengthField() + command.getDataFieldInstruct() + command.getDataMark()
                + oldAddress;
        //获取校验码
        String checkCode = HexadecimalUtil.getCheckCode(message);
        message += checkCode + command.getEndMark();
        DeviceInstruction instruction = new DeviceInstruction();
        //组装DeviceInstruction数据
        instruction.setDtuId(dtuId);
        instruction.setBusinessType(AgreementConstants.InstructBusinessType.OTHER);
        instruction.setProtocolType(protocolType);
        String protocolName = "";
        if (protocolType.equals("1")) {
            protocolName = AgreementConstants.AgreementTypeName.HOUSEHOLD_VALVE;
        } else if (protocolType.equals("2")) {
            protocolName = AgreementConstants.AgreementTypeName.UNIT_VALVE;
        } else if (protocolType.equals("4")) {
            protocolName = AgreementConstants.AgreementTypeName.HOUSEHOLD_HEAT_METER;
        } else if (protocolType.equals("5")) {
            protocolName = AgreementConstants.AgreementTypeName.UNIT_HEAT_METER;
        } else if (protocolType.equals("6")) {
            protocolName = AgreementConstants.AgreementTypeName.SEAHORSE_VALVE_METER;
        }
        instruction.setProtocolName(protocolName);
        instruction.setInstructType(command.getInstructType());
        instruction.setInstructName(command.getInstructName());
        instruction.setPlotId(infoVo.getLotId());
        instruction.setBuildId(infoVo.getBuildId());
        instruction.setUnitId(infoVo.getUnitId());
        instruction.setHouseholdId(infoVo.getHouseholdId());
        instruction.setAddress(infoVo.getAddress());
        instruction.setInstructionSet(message);
        instruction.setBusinessFlag("1");
        return deviceInstructionService.save(instruction);
    }

    /**
     * 通用组装读地址指令表数据
     */
    public boolean readAddress(String protocolType, String instructType, Long dtuId) {
        AgreementCommandPo agreementCommandPo = new AgreementCommandPo();
        agreementCommandPo.setProtocolType(protocolType);
        agreementCommandPo.setType(AgreementConstants.InstructionType.SEND);
        agreementCommandPo.setInstructType(instructType);
        AgreementCommand command = commandService.getProtocolInstruction(agreementCommandPo);
        if (command == null) {
            throw new ServiceException("指令不存在！");
        }
        String message = "";
        message = command.getPrefix() + command.getStartChar() + command.getDeviceType() + "AAAAAAAAAAAAAA"
                + command.getControlCode() + command.getLengthField() + command.getDataFieldInstruct() + command.getDataMark()
        ;
        //获取校验码
        String checkCode = HexadecimalUtil.getCheckCode(message);
        message += checkCode + command.getEndMark();
        DeviceInstruction instruction = new DeviceInstruction();
        //组装DeviceInstruction数据
        instruction.setDtuId(dtuId);
        instruction.setBusinessType(AgreementConstants.InstructBusinessType.OTHER);
        instruction.setProtocolType(protocolType);
        String protocolName = "";
        if (protocolType.equals("1")) {
            protocolName = AgreementConstants.AgreementTypeName.HOUSEHOLD_VALVE;
        } else if (protocolType.equals("2")) {
            protocolName = AgreementConstants.AgreementTypeName.UNIT_VALVE;
        } else if (protocolType.equals("4")) {
            protocolName = AgreementConstants.AgreementTypeName.HOUSEHOLD_HEAT_METER;
        } else if (protocolType.equals("5")) {
            protocolName = AgreementConstants.AgreementTypeName.UNIT_HEAT_METER;
        } else if (protocolType.equals("6")) {
            protocolName = AgreementConstants.AgreementTypeName.SEAHORSE_VALVE_METER;
        }
        instruction.setProtocolName(protocolName);
        instruction.setInstructType(command.getInstructType());
        instruction.setInstructName(command.getInstructName());
        instruction.setPlotId(0L);
        instruction.setBuildId(0L);
        instruction.setInstructionSet(message);
        instruction.setBusinessFlag("1");
        return deviceInstructionService.save(instruction);
    }

    /**
     * 组装指令表数据
     */
    public boolean saveDeviceInstruction(Long dtuId, String address, String instructType, String value) {

        //获取设备信息
        EquipmentInfoVo infoVo = equipmentService.getEquipmentInfoVo(dtuId, address);

        AgreementCommandPo agreementCommandPo = new AgreementCommandPo();
        agreementCommandPo.setProtocolType(AgreementConstants.AgreementType.HOUSEHOLD_VALVE);
        agreementCommandPo.setType(AgreementConstants.InstructionType.SEND);
        agreementCommandPo.setInstructType(instructType);
        AgreementCommand command = commandService.getProtocolInstruction(agreementCommandPo);
        if (command == null) {
            throw new ServiceException("指令不存在！");
        }
        String message = commandService.assemblyHouseholdValveInstruction(command, address, value);

        DeviceInstruction instruction = new DeviceInstruction();
        //组装DeviceInstruction数据
        instruction.setDtuId(dtuId);
        instruction.setBusinessType(AgreementConstants.InstructBusinessType.OTHER);
        instruction.setProtocolType(AgreementConstants.AgreementType.HOUSEHOLD_VALVE);
        instruction.setProtocolName(AgreementConstants.AgreementTypeName.HOUSEHOLD_VALVE);
        instruction.setInstructType(command.getInstructType());
        instruction.setInstructName(command.getInstructName());
        instruction.setPlotId(infoVo.getLotId());
        instruction.setBuildId(infoVo.getBuildId());
        instruction.setUnitId(infoVo.getUnitId());
        instruction.setHouseholdId(infoVo.getHouseholdId());
        instruction.setAddress(infoVo.getAddress());
        instruction.setInstructionSet(message);
        instruction.setBusinessFlag("1");
        return deviceInstructionService.save(instruction);
    }

}
